<?php

namespace app\index\model;

use think\Model;
use think\facade\Session;

use app\index\validate\Topic as Validate;

class Topic extends Model
{
    protected static function init()
    {
        self::observe(\app\index\observer\Topic::class);
    }

    // belongs to user
    public function user()
    {
        return $this->belongsTo('User');
    }

    // belongs to category
    public function category()
    {
        return $this->belongsTo('Category');
    }

    public function replies()
    {
        return $this->hasMany('Reply');
    }

    /**
     * 范围查询-最近回回复排序
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2019-02-25
     * @param    [type]             $query [description]
     * @return   [type]                    [description]
     */
    static public function scopeRecentReplied($query)
    {
        // 按最后更新时间排序
        return $query->order('update_time', 'DESC');
    }

    /**
     * 范围查询-最新发表
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2019-02-25
     * @param    [type]             $query [description]
     * @return   [type]                    [description]
     */
    static public function scopeRecent($query)
    {
        // 按照创建时间排序
        return $query->order('id', 'DESC');
    }

    /**
     * 范围查询-排序方式
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2019-02-25
     * @param    [type]             $query      [description]
     * @param    [type]             $order_type [description]
     * @return   [type]                         [description]
     */
    static public function scopeWithOrder($query, $order_type)
    {
        switch ($order_type) {
            case 'recent':
                $query->recent();
                break;
            default:
                $query->recentReplied();
                break;
        }

        return $query->with('user,category');
    }

    /**
     * 自定义查询方法
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2019-02-25
     * @param    array              $param    请求参数
     * @param    integer            $per_page 每页显示记录数量
     * @return   Pagination                   分页查询结果
     */
    static public function minePaginate($param, $per_page = 10)
    {
        $order_type = NULL;
        if(isset($param['order'])){
            $order_type = $param['order'];
        }
        $self = self::withOrder($order_type);

        foreach ($param as $name => $value) {
            switch ($name) {
                case 'category_id':
                case 'user_id':
                    if($value > 0){
                        $self = $self->where($name, $value);
                    }
                    break;
            }
        }
        $paginate = $self->paginate($per_page);
        return $paginate;
    }

    /**
     * 创建话题记录
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2019-02-15
     * @param    array              $data 表单提交数据
     * @return   Object                   FunctionResult
     */
    static public function createItem($data)
    {
        $res = new FunctionResult('创建话题记录失败');

        $validate = new Validate;
        if(!$validate->scene('create_or_update')->check($data)){
            $res->fail($validate->getError(), []);
            return $res;
        }

        $topic = new self;
        $topic->save($data);

        $res->success('创建话题记录成功', ['id' => $topic->id]);
        return $res;
    }

    /**
     * 更新话题记录
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2019-02-20
     * @param    integer            $id   Topic ID
     * @param    array              $data 表单提交数据
     * @return   Object                   FunctionResult
     */
    static public function updateItem($id, $data)
    {
        $res = new FunctionResult('更新话题记录失败');

        $topic = self::find($id);
        if(empty($topic)){
            $res->fail('未找到话题记录');
            return $res;
        }

        return $topic->updateInfo($data);
    }

    /**
     * 更新话题记录信息
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2019-02-20
     * @param    array              $data 表单提交数据
     * @return   Object                   FunctionResult
    */
    public function updateInfo($data)
    {
        $res = new FunctionResult('更新话题记录信息失败');

        $validate = new Validate;
        if(!$validate->scene('create_or_update')->check($data)){
            $res->fail($validate->getError(), []);
            return $res;
        }

        $current_user = User::currentUser();
        if(empty($current_user)){
            $res->fail('请先登录系统');
            return $res;
        }else if($this->user_id != $current_user->id){
            $res->fail('对不起，您没有权限更新当前话题记录');
            return $res;
        }

        $this->save($data, ['id' => $this->id]);
        $res->success('更新话题记录信息成功', ['id' => $this->id]);
        return $res;
    }

    /**
     * 删除话题记录
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2019-02-20
     * @param    integer            $id   Topic ID
     * @param    array              $data 表单提交数据
     * @return   Object                   FunctionResult
     */
    static public function deleteItem($id, $data)
    {
        $res = new FunctionResult('删除话题记录失败');

        $topic = self::find($id);
        if(empty($topic)){
            $res->success('话题记录已删除', []);
            return $res;
        }

        return $topic->deleteInfo($data);
    }

    /**
     * 判断用户是否可以话题评论记录
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2019-02-27
     * @param    User               $user User Item
     * @return   Object                   FunctionResult
     */
    public function canDelete($user = NULL)
    {
        $res = new FunctionResult('删除话题记录信息失败');

        if(is_null($user)){
            $user = User::currentUser();
        }

        if(empty($user)){
            $res->fail('请先登录系统');
            return $res;
        }else if($this->user_id != $user->id){
            $res->fail('对不起，您没有权限删除当前话题记录');
            return $res;
        }

        $res->success('可以删除');
        return $res;
    }

    /**
     * 删除记录
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2019-02-27
     * @param    array              $data 表单提交数据
     * @return   Object                   FunctionResult
     */
    public function deleteInfo($data)
    {
        $res = new FunctionResult('删除话题记录信息失败');

        if(!is_array($data)){
            $data = [];
        }
        $data['id'] = $this->id;

        $validate = new Validate;
        if(!$validate->scene('delete')->check($data)){
            $res->fail($validate->getError());
            return $res;
        }

        $check_res = $this->canDelete();
        if(!$check_res->status){
            return $check_res;
        }

        $this->delete();
        $res->success('删除话题记录成功', []);
        return $res;
    }
}
